package org.fig.dependency.injection;
/**
 * @Description:{@link Qualifier} 依赖注入
 * @Author: Flynn Vanderboom
 * @Data: 2021/6/22 22:32
 */


import org.fig.dependency.injection.annotation.UserGroup;
import org.fig.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;

@Configuration
public class QualifierAnnotationDependencyInjectionDemo {

    //输出了 primary 的 superUser
    @Autowired
    private User user;


    //限定 输出 user
    @Autowired
    @Qualifier("user")
    private User namedUser;


    @Autowired
    private Collection<User> allUsers; //两个Bean 上面的

    @Autowired
    @Qualifier
    private Collection<User> qualifierUsers; //下面的

    @Autowired
    @UserGroup
    private Collection<User> groupUsers;

    @Bean
    @Qualifier
    public User user1(){
        User user = new User();
        user.setId(8);
        return user;
    }

    @Bean
    @Qualifier
    public User user2(){
        User user = new User();
        user.setId(7);
        return user;
    }


    @Bean
    @UserGroup
    public User user3(){
        User user = new User();
        user.setId(9);
        return user;
    }

    @Bean
    @UserGroup
    public User user4(){
        User user = new User();
        user.setId(10);
        return user;
    }


    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        applicationContext.register(QualifierAnnotationDependencyInjectionDemo.class);

        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(applicationContext);

        String xmlResourcePath = "classpath:META-INF/dependency-lookup-context.xml";

        reader.loadBeanDefinitions(xmlResourcePath);

        applicationContext.refresh();


        QualifierAnnotationDependencyInjectionDemo demo = applicationContext.getBean(QualifierAnnotationDependencyInjectionDemo.class);

        System.out.println("demo.user: "+demo.user);
        System.out.println("demo.namedUser: "+demo.namedUser);
        System.out.println("demo.allUsers: "+demo.allUsers);
        System.out.println("demo.qualifierUser: "+demo.qualifierUsers);
        System.out.println("demo.qualifierUser: "+demo.groupUsers);


        applicationContext.close();
    }

}
